# 固定夹具和公共函数
import pytest
import allure
import yaml
from utils.db_utils import DBUtils
from utils.redis_utils import RedisUtils
from utils.log_utils import LogUtils
from utils.dingtalk_utils import DingTalkUtils
from utils.email_utils import EmailUtils

# 初始化日志
logger = LogUtils.get_logger()

# 读取测试数据
with open("tests/data/test_data.yaml", "r", encoding="utf-8") as f:
    test_data = yaml.safe_load(f)

# 初始化数据库和Redis
db = DBUtils()
redis = RedisUtils()


@pytest.fixture(scope="session")
def setup():
    """测试环境初始化"""
    logger.info("开始测试环境初始化...")
    # 清理测试数据
    db.clear_test_data()
    redis.clear_test_data()
    logger.info("测试环境初始化完成")
    return {
        "db": db,
        "redis": redis,
        "logger": logger,
        "dingtalk": DingTalkUtils(),
        "email": EmailUtils()
    }


@pytest.fixture(scope="function")
def user_auth(setup):
    """用户认证夹具"""
    db = setup["db"]
    logger = setup["logger"]
    # 创建测试用户
    user_id = db.create_test_user()
    logger.info(f"创建测试用户: {user_id}")
    return user_id


def pytest_sessionfinish(session, exitstatus):
    """测试结束后发送通知"""
    if exitstatus == 0:
        status = "成功"
    else:
        status = "失败"

    # 发送钉钉通知
    setup["dingtalk"].send_message(f"接口自动化测试执行完成，状态: {status}")

    # 发送邮件通知
    setup["email"].send_email(f"接口自动化测试执行完成，状态: {status}")
